package com.ns.dcjh.ui.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.PlaybackException;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.ui.PlayerView;
import com.ns.dcjh.R;

public class VideoPalyActivity extends AppCompatActivity {
    private SimpleExoPlayer mPlayer;
    private PlayerView mPlayerView;
    private ImageView mBackView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_video);

        mPlayerView = findViewById(R.id.player_view);
        mBackView = findViewById(R.id.player_back);

        Bundle bundle = getIntent().getExtras();
        if(bundle != null && bundle.getString("url") != null){
            String videoUrl = bundle.getString("url");
            // 创建媒体播放器
            mPlayer = new SimpleExoPlayer.Builder(this).build();
            mPlayerView.setPlayer(mPlayer);
            MediaItem mediaItem = MediaItem.fromUri(videoUrl);
            mPlayer.setMediaItem(mediaItem);
            mPlayer.prepare();
            mPlayer.addListener(new Player.Listener() {
                @Override
                public void onPlayerError(PlaybackException error) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(VideoPalyActivity.this,"视频编码或格式有问题，请检查视频编码或格式，或请下载用系统相机查看",Toast.LENGTH_LONG).show();
                        }
                    });
                }
            });
            mPlayer.setPlayWhenReady(true);
        }
        mBackView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    //        以下是生命周期管理
    @Override
    protected void onStart() {
        super.onStart();
        mPlayerView.onResume();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mPlayerView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPlayer.release();
    }

    //        注意：在使用ExoPlayer时，需要在Activity中保持屏幕常亮以避免视频播放过程中屏幕自动关闭。
    @Override
    protected void onResume() {
        super.onResume();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    @Override
    protected void onPause() {
        super.onPause();
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }
}